<?php
require_once 'vendor/autoload.php';

/**
 * 消息推送驱动器组件：SMS.E106818SMS[消息子模型-SMS.蝶信/至臻/E企信通]
 * 
 * @date	2017年7月19日 下午1:05:53
 * 
 */
class MessagePusherSms_E106818SMS extends CI_Driver implements libraries\common\MessagePusherInterface
{
	const DEBUG_MODE = false;
	private $userName    = "";		//必选	string	帐号名称
	private $userPass    = "";		//必选	string	密码
	private $subid       =   "";			//选填	string	通道号码末尾添加的扩展号码
	//private $url         = 'http://114.215.87.64:8082/SendMT/SendMessage';
	private $url         = 'http://115.28.112.245:8082/SendMT/SendMessage';//至臻
	private $lastResponse       = null;
	//蝶信企信通安全说明函: http://120.106818.com/SendMTU8/SendMessage_utf8.aspx
	
	public function __set($var, $val)
	{
		$this->$var = $val;
	}
	
	public function __construct($config = array())
	{
		
	}
	
	/**
	 * 给定数据执行推送
	 *
	 * @param array $data
	 *
	 * @return void
	 */
	public function pushPerform($data)
	{
		if(self::DEBUG_MODE) {
			return ;
		}
		$mobile  = $data['mobile'];
		$message = $data['msg'];
		$this->lastResponse = $this->send($mobile, $message);
	}
	
	/**
	 * 获取上一次推送的状态
	 *
	 * @return boolean
	 */
	public function getStatus()
	{
		if(self::DEBUG_MODE) {
			return true;
		}
		
		/*
		 * 返回格式
		 * 成功响应     00,F003233140527170802  多个手机号发送成功
		 * 成功响应     03,F003233140527170802  个手机号发送成功
		 *
		 * 多/单个手机号发送成功, 将返回“状态码，响应ID”匹配状态报告时，请将响应ID+手机号匹配到唯一短消息
		 * 响应ID格式：一位字母+18位数字
		 */
		list($code, $rid) = $this->getParsedResponse();
		if(in_array($code, array('00', '03'))){
			return true;
		}
		
		return false;
	}
	
	public function getMessage()
	{
		$errorMsg = array(
				'00' => '多个手机号请求发送成功',
				'02' => 'IP限制',
				'03' => '单个手机号请求发送成功',
				'04' => '用户名错误',
				'05' => '密码错误',
				'06' => '编码错误',
				'07' => '发送时间有误',
				'08' => '参数错误',
				'09' => '手机号码有误',
				'10' => '扩展号码有误',
				'11' => '余额不足',
				'-1' => '服务器内部异常',
				'REJECT' => '非法消息内容',
		);
		
		list($code, $rid) = $this->getParsedResponse();
		
		if(isset($code)) {
			return !empty($errorMsg[$code]) ? $errorMsg[$code] : $code;
		}
		
		return false;
	}
	
	private function getParsedResponse()
	{
		if(!isset($this->lastResponse)) {
			//FIXME trigger_error???
			//trigger_error(sprintf("%s::%s: You Shouldn't call me here, because no response now!", __CLASS__, __METHOD__), E_USER_ERROR);
			return false;
		}
		
		$response = $this->lastResponse;
		
		$array = explode(',', $response);
		
		//print_r($array);
		return $array;
	}
	
	private function send($mobile, $message)
	{
		$params = array(
				'UserName'  => $this->userName,
				'UserPass'  => $this->userPass,
				'subid'     => $this->subid,
				'Mobile'    => $mobile,
				'Content'   => $message,
		);
		
		$this->pushUrl = $this->url . '?' . http_build_query($params);
		try {
			$request = Requests::get($this->pushUrl);
		} catch (\Exception $e) {
			//var_dump($e);
			return null;
		}
		
		$response = $request->body;
		
		return $response;
	}
	
}